package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.collect.Lists;
import com.zzyl.constant.Constants;
import com.zzyl.dto.LoginDto;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtConfigProperties;
import com.zzyl.service.CustomerUserService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;

@Service
public class CustomerUserServiceImpl implements CustomerUserService {


    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    JwtConfigProperties jwtConfigProperties;

    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );


    @Override
    public LoginVo userLogin(UserLoginRequestDto dto) {
        //用前端传递的 appid appsecret code 获取openId
        String openid = wechatService.getOpenid(dto.getCode());
        //根据openId 查询客户信息
        Member member =  memberMapper.selectByOpenId(openid);
        //判断用户是否存在, 如果为空创建用户, 并给openid赋值
        if (BeanUtil.isEmpty(member)){
             member = Member.builder().openid(openid).build();
        }
        //根据code 去微信获取手机号
        String phone = wechatService.getPhone(dto.getPhoneCode());
        //去数据库新增或修改用户信息
        insertOrUpdate(member,phone);
        //根据用户id和昵称生成jwt令牌返回给小程序
        HashMap<String, Object> map = new HashMap<>();
        map.put(Constants.JWT_USERID,member.getId());
        map.put(Constants.JWT_USERNAME,member.getName());
        String jwt = JwtUtil.createJWT(jwtConfigProperties.getBase64encodedsecretkey(),
                jwtConfigProperties.getTtl(),map);
        LoginVo vo = new LoginVo();
        vo.setToken(jwt);
        vo.setNickName(member.getName());
        return vo;
        //校验token
    }

    private void insertOrUpdate(Member member, String phone) {
        //手机号不相等更新手机号
        if (! phone.equals(member.getPhone())){
            member.setPhone(phone);
        }
        //根据id判断是新增还是修改
        if ( member.getId() != null){
            memberMapper.update(member);
            return;
        }
//随机组装昵称，词组+手机号后四位
        String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                + StringUtils.substring(member.getPhone(), 7);

        member.setName(nickName);
        memberMapper.insert(member);
    }
}
